package com.youku.component.script;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.youku.exception.ScriptExecuteException;
import com.youku.util.RemoteShellTool;

public class ShellRunner implements ScriptRunner {

	private static final Logger logger = LoggerFactory.getLogger(ShellRunner.class);

	public void execute(String script) {

		// executeLocalShell(script);

		executeRemoteShell("10.10.73.46", 22022, "root", "pvnd3SPRA6qY", script);

	}

	private void executeLocalShell(String script) {
		try {
			logger.info("执行了shell脚本: {}", script);
			Process process = Runtime.getRuntime().exec(script);

			int exeRs = process.waitFor();

			if (exeRs != 0)
				throw new ScriptExecuteException("执行脚本" + script + "之后未能正常结束，异常的执行结果返回码为" + exeRs);
		} catch (IOException e) {
			throw new IllegalArgumentException("找不到该脚本文件" + script, e);
		} catch (InterruptedException e) {
			throw new ScriptExecuteException("获取脚本执行结果的时候被打断", e);
		}
	}

	private void executeRemoteShell(String ip, int port, String user, String password, String script) {
		RemoteShellTool tool = new RemoteShellTool(ip, port, user, password);

		logger.info("正在执行远程服务器{}上的脚本文件{}，请等待片刻...", ip, script);
		String result = tool.exec(script);

		logger.debug("脚本执行输出：" + result);

		logger.info("脚本文件执行完成，继续执行后面的流程...");
	}

}
